package com.jhd.jiangxi;

import com.alibaba.fastjson.JSON;
import com.jhd.jiangxi.service.VaccineService;
import com.jhd.jiangxi.vo.AuthToken;
import com.jhd.jiangxi.vo.JsonForResult;

import net.zigin.commons.util.ParamsMapUtil;
import net.zigin.commons.util.StringUtil;

import java.io.IOException;
import java.util.Map;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Call;
import retrofit2.Retrofit;

public class NetInterceptor implements Interceptor {
    private ScanApplication application;

    public NetInterceptor(ScanApplication application) {
        this.application = application;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);//执行请求
        //String responseBodyStr = handResponse(response);//获得处理后的数据字符串
        if (response.code() == 401 || response.code() == 403) {//判断是否token过期
//            responseBodyStr = handResponse(chain.proceed(RequestUtils.reRequest(request)));
            String username = application.getUserName();
            String password = application.getPassword();

            if (username == null || password == null) return response;
            Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API(application.getBackSystem()));//new Retrofit.Builder().baseUrl(UtilHelper.baseUrls.API).addConverterFactory(FastJsonConverterFactory.create()).build();
            VaccineService vs = retrofit.create(VaccineService.class);
            Map<String, String> params = ParamsMapUtil.getInstance("username", username)
                    .addParam("password", password).addParam("type", "password");

            Call<JsonForResult> jsonForResultCall = vs.getAuthInfo(params);
            JsonForResult jsonForResult = jsonForResultCall.execute().body();
            if (jsonForResult != null && jsonForResult.isSuccess()) {
                AuthToken authToken = JSON.parseObject(jsonForResult.getData().toString(), AuthToken.class);
                if (authToken == null || StringUtil.isNullOrEmpty(authToken.getAccessToken())) {
                    //Toast.makeText(application.getBaseContext(), "自动登录失败,请到注销后重新登录!", Toast.LENGTH_SHORT).show();
                    throw new IOException("登录token过期,请注销重新登录!");
                }
                String accessToken = authToken.getAccessToken();
                application.setAccessToken(accessToken);
                Request newRequest = request.newBuilder().header("Authorization", application.getAccessToken()).build();
                response.body().close();
                return chain.proceed(newRequest);
            } else {
                throw new IOException(jsonForResult.getMessage());
            }
        } else if (response.code() > 300) {
            String error = "接口调用没有成功!http编码:" + response.code();
            if (StringUtil.isNullOrEmpty(response.message()) == false) {
                error = error + "." + response.message();
            }
            throw new IOException(error);
        }
        return response;
    }

//    private String handResponse(Response response) throws IOException {
//        String passWord = "chrischen";//加密解密专用密码
//        ResponseBody responseBody = response.body();
//        String responseBodyStr = responseBody.string();
//        String requestUrl = response.request().url().url().toString();//请求路径
//        //MsgUtils.show("MobileAPI:" + requestUrl + "  返回数据==>" + responseBodyStr);
//        return responseBodyStr;
//    }
}